//
//  NetHandle.m
//  网络请求_封装_老师版
//
//  Created by 李书勋 on 14/12/4.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "NetHandle.h"

@implementation NetHandle
+(void)getDataWithURL:(NSString *)str completion : (void(^)(NSData *data))block
{
    NSString *urlStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    request.HTTPMethod = @"GET";
    
    
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSLog(@"连接错误信息:%@", connectionError);
        
        // 处理数据
        // 确定一个地址
        
        
        
        NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString *docPath = [arr lastObject];
        
        NSString *path = [NSString stringWithFormat:@"%@/%ld.aa", docPath,[str hash]];
        
        
        
        if (data != nil) {
            // 将返回的数据不为空, 就调用block
            
          BOOL result = [NSKeyedArchiver archiveRootObject:data toFile:path];
            NSLog(@"存储结果:%d", result);
            
            block(data);
            
            
        } else{
            // 当没有数据,怎么做....
            
            // 没有网路/请求失败 就从本地读取最近的一次成功数据
            NSData *pickData = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
            if (pickData != nil) {
                block(pickData);
            }
            
        }
        
        
        // 处理数据
        // 让有关数据  刷新视图
        // [tableView reloadData];
        // label.text ......
        
        
        
        
    }];
}
@end
